package Listeners;

import DAO.DbDao;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.ResultSet;

/**
 * Created by hadoop on 17-6-14.
 * 监听请求，同时将用户会话加入到online_info表中
 */
@WebListener
public class RequestListener implements ServletRequestListener{
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        HttpServletRequest request = (HttpServletRequest) servletRequestEvent.getServletRequest();
        HttpSession session = request.getSession();
        String sid = session.getId();
        String ip = request.getRemoteAddr();
        String uri = request.getRequestURI();
        String user = (String) session.getAttribute("username");
        user = (user == null) ? "visitor" : user;
        DbDao dao = (DbDao) servletRequestEvent.getServletContext().getAttribute("DbDao");
        try {
            ResultSet rs = dao.query("select * from online_info where sid = '"+sid+"'");

            if(rs.next()){
                rs.updateString(2,user);
                rs.updateString(4,uri);
                rs.updateLong(5,System.currentTimeMillis());
                rs.updateRow();
                rs.close();
            }else{
                dao.insert("insert into online_info values(?,?,?,?,?)",sid,user,ip,uri,System.currentTimeMillis());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {

    }
}
